package service

import (
	"os"

	"file_explorer/common/consts"
	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"

	"github.com/laurent22/go-trash"
)

// 创建文件或目录
func CreateFile(fileInfo *model.FileInfo) error {
	path := fileInfo.GetPath()

	if fileInfo.Type == consts.FileTypeDir {
		err := util.MkdirIfNotExist(path)
		if err != nil {
			log.Error("create dir failed, path=%v, err=%v", path, err)
			return err
		}
		log.Debug("create dir success, info=%v", fileInfo)
		return nil
	}

	if fileInfo.Type != consts.FileTypeRegular {
		log.Warn("create invalid file type=%v", fileInfo.Type)
		return nil
	}

	// 创建空白文件
	_, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
	if err != nil {
		log.Error("create file failed, path=%v, err=%v", path, err)
		return err
	}

	log.Debug("create file success, info=%v", fileInfo)

	return nil
}

func DeleteFile(fileInfos []*model.FileInfo) error {
	for _, fileInfo := range fileInfos {
		_, err := trash.MoveToTrash(fileInfo.GetPath())
		if err != nil {
			log.Error("delete file failed, path=%v, err=%v", fileInfo.GetPath(), err)
			return err
		}
	}

	log.Debug("delete files success, fileInfos=%v", fileInfos)

	return nil
}
